package com.atguigu.gmall.cart.controller;


import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.bo.UserIdBo;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/api/cart")
@RestController
public class CartRestController {


    @Autowired
    CartService cartService;

    /**
     * 购物车商品列表
     * @return
     */
    @GetMapping("/cartList")
    public Result cartList() {
        UserIdBo bo = AuthContextHolder.getUserIdBo();
        //1、查询购物车中的所有商品
        List<CartInfo> cartInfos = cartService.getCartList(bo.getUserId(),bo.getUserTempId());

        //
        return Result.ok(cartInfos);
    }


    /**
     * 更新购物车某个商品数量
     * @param skuId
     * @param skuNum
     * @return
     */
    @PostMapping("/addToCart/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable("skuId")Long skuId,@PathVariable("skuNum")Integer skuNum){

        UserIdBo bo = AuthContextHolder.getUserIdBo();
        String cartKey = cartService.determinCartKey(bo.getUserId(), bo.getUserTempId());
        cartService.addToCart(cartKey,skuId,skuNum);
        return Result.ok();
    }


    /**
     * 删除购物车商品
     * @param skuId
     * @return
     */
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCartSku(@PathVariable("skuId")Long skuId){
        UserIdBo bo = AuthContextHolder.getUserIdBo();
        String cartKey = cartService.determinCartKey(bo.getUserId(), bo.getUserTempId());
        //删除指定购物车中的指定商品
        cartService.deleteCartItem(cartKey,skuId);
        return Result.ok();
    }


    /**
     * 选中、不选中购物车的商品
     */
    @GetMapping("/checkCart/{skuId}/{checked}")
    public Result checkCart(@PathVariable("skuId") Long skuId,
                            @PathVariable("checked") Integer checked){

        UserIdBo bo = AuthContextHolder.getUserIdBo();
        String cartKey = cartService.determinCartKey(bo.getUserId(), bo.getUserTempId());

        //选中、不选中某个商品
        cartService.checkedItem(cartKey,skuId,checked);
        return Result.ok();
    }
}
